package com.example.schoolexam2.utils;

import com.example.schoolexam2.entity.Employee;
import com.example.schoolexam2.entity.Student;
import com.example.schoolexam2.vo.StudentVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JwtUtils {
    private static final String APP_SECRET="Fanship12138";
    /**
     * 构建token的主题
     */
    private static final String SUBJECT = "fanship-exam";
    /**
     * 过期时间为1天
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24;


    public static String studentgenJsonWebToken(Student student) {
        if (student ==null|| student.getStudentId()==null || student.getPassword()==null){
            return null;
        }
        return Jwts.builder().setSubject(SUBJECT)
                //下面三行设置token中间字段，携带用户信息
                .claim("studentId",student.getStudentId())
                .claim("studentName",student.getStudentName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                .signWith(SignatureAlgorithm.HS256,APP_SECRET)
                .compact();   //生成的结结果集字符太长，这里压缩一下
    }

    public static String employeegenJsonWebToken(Employee employee){
        if (employee ==null || employee.getEmployeeId()==null || employee.getPassword()==null){
            return null;
        }
        return Jwts.builder().setSubject(SUBJECT)
                .claim("id",employee.getEmployeeId())
                .claim("name",employee.getEmployeeName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                .signWith(SignatureAlgorithm.HS256,APP_SECRET)
                .compact();
    }

    //校验token
    public static Claims checkToken(String token){
        try {
            return Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
        }catch (Exception e){
            return  null;
        }
    }

    //加密密码的方法
    public static  String addM(String pwd) throws UnsupportedEncodingException {
        String s = DigestUtils.md5DigestAsHex(pwd.getBytes("UTF-8")); 
        return s;
    }
}
